/**
 * 
 * @authors Your Name (you@example.org)
 * @date    2016-10-26 17:41:22
 * @version $Id$
 *
 *
 * 加载历史信息模块
 *    下载历史信息
 *    渲染页面
 *    图片延时加载
 *    
 *
 */

;(function(root,factory){

  if(typeof exports === 'object' && typeof module === 'object'){
    
    factory(exports);

  } else if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['exports'], factory);
  } else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
    // CommonJS
    factory(exports);
  } else {
    // Browser globals
    if (!root._s) {
      root._s = {};
    }
    factory(root);
  }
})(typeof window !== 'undefined' ? window : this ,function(exports, undefined){
  'use strict';

  function moduleInit($, log, conf, _, utils, options){

    var urlConf = conf._conf;       //存储配置信息
    var _ = _||{};       
    var pubsub = utils.pubSub()||{};
    var callback = {};
    var callbackFuc = utils.callbackFuc;
    var setUrl = utils.setUrl;


    pubsub.addEvent('getHistoryData', function(data){
      if (data.code === 0) {
        pubsub.fireEvent('rendered',renderHistory(data.data));
      }
    });
    pubsub.addEvent('newMsgTip', function(data){
      tip();
    });
    pubsub.addEvent('rendered', function(data){
      pubsub.fireEvent('imgDefer',data);
    });

    function receiver(identifier, options){
      var deferr = null;
      switch(identifier){
        case 'history':
          deferr = getHistory(options);
          deferr.then(function(data){
            /*
              回调通知数据获取完毕

            */
            pubsub.fireEvent('getHistoryData',data);
          });
        break;
        case 'realMsg':
          pubsub.fireEvent(identifier, renderOneMsg(options));
          toFloor();
        break;
        case 'sseUser':
          getSse(identifier, options)
        break;
      }
      
      if (deferr) {
        deferr.then(function(data){
          /*
            回调通知数据获取完毕
          */
          pubsub.fireEvent(identifier,data);
        });
      }

        
    };

    /*
      M
    */
    /*
      获取历史消息列表
    */
    function getHistory(options){
      /*
        获取历史消息
      */
      var deferr = $.ajax({
        url: urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.msgList,
        type: 'GET',
        dataType: 'json',
        data: {
          thread_id : options.thread_id
        }
      })
      .done(function(data) {
        if (data.code === 0) {

          for(var k in data.data){
            if (data.data[k].type === '1') {

              data.data[k].msg = setUrl(data.data[k].msg);
            }else{
              data.data[k].msg = urlConf.root + data.data[k].msg;
              data.data[k].thumb = data.data[k].msg.replace('uploads/kf/','uploads/kf/');
            }
          }

        }else if(data.code === 100){
          window.location.href = urlConf.root + urlConf.static + 'login.php';
        }
          
      })
      .fail(function() {
        log._log("error");
      })
      .always(function() {
        log._log("complete");
      });
      
      return deferr;
    }
    /*
      启动服务器推送
    */
    function getSse(identifier,options){
      
      var sse = new EventSource(urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.sseUser + '?thread_id=' + options.thread_id);

      /*
        服务器推送消息
      */

      sse.onmessage = function(data){

        var data = JSON.parse(data.data);
        if (typeof data !== 'undefined' && data.code === 0) {
          
          for(var k in data.data){
            if (data.data[k].type === '1') {

              data.data[k].msg = setUrl(data.data[k].msg);
            }else{
              data.data[k].msg = urlConf.root + data.data[k].msg;
              data.data[k].thumb = data.data[k].msg.replace('uploads/kf/','uploads/kf/thumbnail/');
            }
          }
          pubsub.fireEvent('startImgDeferrs', renderOneMsg(data.data));
          pubsub.fireEvent('newMsgTip');
        }
      };

    }

    /*
      V
    */
    /*
      渲染历史消息列表
    */
    function renderHistory(data){
      
      var msgItemTpl = $('#msgItemTpl');

      $('.chat-container').html(_.template(msgItemTpl.html())({list: data}));

      $('body')[0].scrollTop = $('.jsService').height()-$(window).height();


      return {code:0};

    }
    /*
      渲染单条消息
    */
    function renderOneMsg(data){
      console.log(data.length);

      var msgItemTpl = $('#msgItemTpl');
      var str = '';
      for(var i=0 ; i<data.length ; i++){
        if (data[i].type === '2') {
          pubsub.fireEvent('startImgDeferrs', data[i]);
        }
        str += _.template(msgItemTpl.html())({list: [data[i]]});
      }
      
      $('.chat-container').append(str);

      return {code:0, data: data};
    }

    /*
      C
    */

    function tip(){
      $('.has-msg').removeClass('s-hide');
      setTimeout(function(){
        $('.has-msg').addClass('s-hide');
      },2000);
    }

    function toFloor(){
      $('body')[0].scrollTop = $('.jsService').height()-$(window).height();
    }


    return {
      set: function(identifier, callbacks){
        callback[identifier] = [callbacks];

        pubsub.addEvent(identifier, function(data){
          console.log(callback[identifier]);
          callbackFuc(callback[identifier],data);
        });
      },
      start: function(identifier, options){
        receiver(identifier, options);
      }
    };
  }

  exports.msg = moduleInit;

});